package com.wms.controller;

import com.wms.bean.ResultBean;
import com.wms.core.R;
import com.wms.service.ZhiJianService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = "图片上传(质检)")
public class UplaodController {
    private final String IMAGE_URL="/images/";
    @Autowired
    HttpServletRequest request;
    @Autowired
    ZhiJianService zhiJianService;


    /**
     * 实现图片上传
     * @param file
     * @return
     */
    public String topian(MultipartFile file){
        //新的文件名
        String newFileName=newFile(file);

        //存储目录
        String ymd=getYMD();

        //获取文件在服务器上的存储目录
        String root = request.getServletContext().getRealPath("/");
        File dir = new File(root + IMAGE_URL+ymd+"/");
        if (!dir.exists())
            dir.mkdirs();//创建目录
        //将file文件 写入到指定目录 下
        try {
            //将文件写入web根目录下的 images文件夹下
            file.transferTo(new File(root+IMAGE_URL+ymd+"/", newFileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return IMAGE_URL+ymd+"/"+newFileName;
    }

    //获取新的文件名
    public String newFile (MultipartFile file){
        //获取原始文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀
        String[] tmp = fileName.split("[.]");
        int len = tmp.length;
        //新的文件名
        String newFileName = System.currentTimeMillis() + "." + tmp[len - 1];
        return newFileName;
    }

    //获取当前时间
    String getYMD(){
        LocalDate localDate=LocalDate.now();
        return localDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
    }



    @ApiOperation("质检图片上传")
    @PostMapping(value = "/addTPS",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultBean addTPS(@RequestPart("file") MultipartFile file,int id) {
        String url = topian(file); // 复用已有的 topian 方法
        System.out.println("图片地址:"+url);

        int n=zhiJianService.tupian(id,url);
        return R.success("图片上传", url);
    }


}
